package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    /**
     * 新增地址簿
     */
    @Override
    public void addAddressBook(AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        if(addressBookUpsertReqDTO == null){
            throw new BadRequestException("参数为空");
        }
        AddressBook addressBook = BeanUtil.copyProperties(addressBookUpsertReqDTO, AddressBook.class);
        addressBook.setUserId(UserContext.currentUser().getId());
        String[] split = addressBookUpsertReqDTO.getLocation().split(",");
        addressBook.setLon(Double.parseDouble(split[1]));
        addressBook.setLat(Double.parseDouble(split[0]));
        addressBook.setIsDeleted(0);
        addressBook.setCreateBy(UserContext.currentUser().getId());
        addressBook.setUpdateBy(UserContext.currentUser().getId());
        addressBook.setCreateTime(LocalDateTime.now());
        addressBook.setUpdateTime(LocalDateTime.now());
        Long userId = UserContext.currentUserId();
        if(addressBook.getIsDefault() == 1){
            lambdaUpdate().eq(AddressBook::getUserId, userId)
                    .set(AddressBook::getIsDefault, 0)
                    .update();
        }
        save(addressBook);
    }

    /**
     * 分页查询地址簿
     */
    @Override
    public PageResult<AddressBook> pageAddressBook(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
        Long userId = UserContext.currentUser().getId();
        //调用mapper查询数据，这里由于继承了ServiceImpl<ServeMapper, Serve>，使用baseMapper相当于使用ServeMapper
        return PageHelperUtils.selectPage(addressBookPageQueryReqDTO,
                () -> baseMapper.queryList(userId));
    }

    /**
     * 地址薄修改
     */
    @Override
    public void updateAddressBook(Long id, AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        if(addressBookUpsertReqDTO == null){
            throw new BadRequestException("参数为空");
        }
        AddressBook addressBook = BeanUtil.copyProperties(addressBookUpsertReqDTO, AddressBook.class);
        addressBook.setId(id);
        addressBook.setUpdateBy(UserContext.currentUser().getId());
        addressBook.setUpdateTime(LocalDateTime.now());
        updateById(addressBook);
    }

    /**
     * 批量删除地址簿
     * 逻辑删除
     */
    @Override
    public void deleteAddressBook(List<String> ids) {
        if(CollectionUtil.isNotEmpty(ids)){
            // 自定义SQL
            List<Long> collect = ids.stream().map(id -> Long.parseLong(id)).collect(Collectors.toList());
            UpdateWrapper<AddressBook> delete = new UpdateWrapper<AddressBook>().in("id", collect).set("is_deleted", 1);
            // 批量逻辑删除
            update(delete);
        }
    }

    /**
     * 设置默认地址
     */
    @Override
    public void setDefaultAddress(Long id, Integer flag) {
        if(id == null && flag == null){
            throw new BadRequestException("参数不全");
        }
        Long userId = UserContext.currentUserId();

        lambdaUpdate().eq(AddressBook::getUserId, userId)
                .set(AddressBook::getIsDefault, 0)
                .update();

        AddressBook addressBook = baseMapper.selectById(id);
        addressBook.setIsDefault(flag==1?flag:1);
        baseMapper.updateById(addressBook);
    }

    /**
     * 获取默认地址
     */
    @Override
    public AddressBook defaultAddress() {
        Long userId = UserContext.currentUserId();
        return lambdaQuery().eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, 1)
                .one();
    }
}
